<template>
  <view class="bind-mobile-page">
    <!-- 顶部提示 -->
    <view class="top-section">
      <image class="logo-img" src="/static/images/dog_logo.png" mode="widthFix"></image>
      <view class="subtitle-text">请绑定手机号以继续使用</view>
    </view>

    <!-- 表单区域 -->
    <view class="form-section">
      <!-- 手机号输入 -->
      <view class="form-item">
        <view class="form-label">
          <text class="required">*</text>
          <text>手机号</text>
        </view>
        <input
          class="form-input"
          type="number"
          v-model="form.mobile"
          placeholder="请输入手机号"
          maxlength="11"
        @blur="handleMobileBlur"
        />
      </view>

      <!-- 验证码输入 -->
      <view class="form-item">
        <view class="form-label">
          <text class="required">*</text>
          <text>验证码</text>
        </view>
        <view class="code-input-wrapper">
          <input
            class="form-input code-input"
            type="number"
            v-model="form.code"
            placeholder="请输入验证码"
            maxlength="6"
          />
          <button
            class="code-btn"
            :class="{ disabled: btnDisabled }"
            :disabled="btnDisabled"
            @click="sendCode"
          >
            {{ btnText }}
          </button>
        </view>
      </view>

      <!-- 提交按钮 -->
      <button class="submit-btn" @click="submitBind" :loading="submitting">
        {{ submitting ? '绑定中...' : '确认绑定' }}
      </button>

      <!-- 温馨提示 -->
      <view class="tips-section">
        <text class="tips-icon">ℹ️</text>
        <text class="tips-text">绑定成功后将自动返回</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import { sendSmsCode, bindUserMobile, checkMobileExists } from '@/api/mobile';
import Toast from '@/utils/toast';
import { useUserStoreHook } from '@/store/user';

// 表单数据
const form = ref({
  mobile: '',
  code: ''
});

// 验证码按钮状态
const btnText = ref('获取验证码');
const btnDisabled = ref(false);
const countdown = ref(0);
let timer: any = null;

// 提交状态
const submitting = ref(false);

// 用户ID
const user_id = ref(0);

// 返回地址
const returnUrl = ref('');

// 手机号校验信息
const mobileCheckInfo = ref({
  mobile: '',
  exists: false,
  nickname: '',
  userId: null as number | null,
  confirmed: false,
});
const mobileCheckLoading = ref(false);
let mobileCheckRequestId = 0;

const resetMobileCheckInfo = () => {
  mobileCheckInfo.value = {
    mobile: '',
    exists: false,
    nickname: '',
    userId: null,
    confirmed: false,
  };
};

const runMobileCheck = async (mobile: string) => {
  if (!mobile) {
    resetMobileCheckInfo();
    return mobileCheckInfo.value;
  }

  const requestId = ++mobileCheckRequestId;
  mobileCheckLoading.value = true;

  try {
    const res: any = await checkMobileExists({
      mobile,
      user_id: user_id.value || 0,
    });

    if (mobileCheckRequestId !== requestId) {
      return mobileCheckInfo.value;
    }

    if (res.result === 1) {
      const exists = !!(res.data && res.data.exists);
      const userData = res.data && res.data.user ? res.data.user : {};
      mobileCheckInfo.value = {
        mobile,
        exists,
        nickname: userData.nickname || '',
        userId: userData.uid ?? null,
        confirmed: false,
      };

      if (exists) {
        // 提示将在提交时二次弹窗
      }
    } else {
      resetMobileCheckInfo();
      Toast.error(res.msg || '手机号校验失败');
    }
  } catch (error) {
    console.error('检查手机号是否已绑定失败:', error);
    if (mobileCheckRequestId === requestId) {
      resetMobileCheckInfo();
    }
    Toast.error('手机号校验失败，请稍后重试');
  } finally {
    if (mobileCheckRequestId === requestId) {
      mobileCheckLoading.value = false;
    }
  }

  return mobileCheckInfo.value;
};

const ensureMobileCheck = async () => {
  const mobile = form.value.mobile ? form.value.mobile.trim() : '';

  if (!mobile || !/^1[3-9]\d{9}$/.test(mobile)) {
    resetMobileCheckInfo();
    return null;
  }

  if (
    mobileCheckInfo.value.mobile === mobile &&
    !mobileCheckLoading.value &&
    mobileCheckInfo.value.mobile
  ) {
    return mobileCheckInfo.value;
  }

  return await runMobileCheck(mobile);
};

const handleMobileBlur = async () => {
  await ensureMobileCheck();
};

/**
 * 页面加载时获取用户ID和返回地址
 */
onMounted(async () => {
  await useUserStoreHook().getSign();
  user_id.value = uni.getStorageSync('user_id') || 0;
  
  if (!user_id.value) {
    Toast.error('请先登录');
    // setTimeout(() => {
    //   uni.reLaunch({
    //     url: '/pages/login/bind-mobile'
    //   });
    // }, 1500);
    return;
  }
  
  console.log('当前用户ID:', user_id.value);
});

/**
 * 发送验证码
 */
const sendCode = async () => {
  // 验证手机号
  if (!form.value.mobile) {
    Toast.error('请输入手机号');
    return;
  }
  
  if (!/^1[3-9]\d{9}$/.test(form.value.mobile)) {
    Toast.error('手机号格式错误');
    return;
  }
  
  const checkResult = await ensureMobileCheck();
  if (checkResult && checkResult.exists) {
    return;
  }

  // 开始倒计时
  startCountdown();
  
  try {
    const res: any = await sendSmsCode({
      mobile: form.value.mobile
    });
    
    if (res.result === 1) {
      Toast.success('验证码已发送');
    } else {
      // 发送失败，停止倒计时
      stopCountdown();
      Toast.error(res.msg || '验证码发送失败');
    }
  } catch (error) {
    console.error('发送验证码失败:', error);
    stopCountdown();
    Toast.error('网络错误，请稍后重试');
  }
};

/**
 * 开始倒计时
 */
const startCountdown = () => {
  countdown.value = 60;
  btnDisabled.value = true;
  btnText.value = `${countdown.value}s`;
  
  timer = setInterval(() => {
    countdown.value--;
    btnText.value = `${countdown.value}s`;
    
    if (countdown.value <= 0) {
      stopCountdown();
    }
  }, 1000);
};

/**
 * 停止倒计时
 */
const stopCountdown = () => {
  if (timer) {
    clearInterval(timer);
    timer = null;
  }
  countdown.value = 0;
  btnDisabled.value = false;
  btnText.value = '获取验证码';
};

/**
 * 提交绑定
 */
const submitBind = async () => {
  // 验证表单
  if (!form.value.mobile) {
    Toast.error('请输入手机号');
    return;
  }
  
  if (!/^1[3-9]\d{9}$/.test(form.value.mobile)) {
    Toast.error('手机号格式错误');
    return;
  }
  
  const checkResult = await ensureMobileCheck();
  if (checkResult && checkResult.exists) {
    if (!mobileCheckInfo.value.confirmed) {
      const nickname = mobileCheckInfo.value.nickname || '其他用户';
      const userConfirmed = await new Promise<boolean>((resolve) => {
        uni.showModal({
          title: '提示',
          content: `手机号已被${nickname}绑定，是否继续？`,
          confirmText: '继续',
          cancelText: '取消',
          success: (res) => resolve(res.confirm),
          fail: () => resolve(false),
        });
      });

      if (!userConfirmed) {
        submitting.value = false;
        return;
      }

      mobileCheckInfo.value = {
        ...mobileCheckInfo.value,
        confirmed: true,
      };
    }
  }

  if (!form.value.code) {
    Toast.error('请输入验证码');
    return;
  }
  
  // 开始提交
  submitting.value = true;
  
  try {
    const res: any = await bindUserMobile({
      user_id: user_id.value,
      mobile: form.value.mobile,
      code: form.value.code,
      force: mobileCheckInfo.value.confirmed ? 1 : 0,
    });
    
    if (res.result === 1) {
      // 绑定成功，更新本地缓存
      uni.setStorageSync('phone', form.value.mobile);
      
      console.log('✅ 手机号绑定成功:', form.value.mobile);
      
      Toast.success('手机号绑定成功');
      
      // 延迟跳转
      setTimeout(() => {
        handleReturn();
      }, 1000);
    } else {
      submitting.value = false;
      Toast.error(res.msg || '绑定失败');
    }
  } catch (error) {
    submitting.value = false;
    console.error('绑定失败:', error);
    Toast.error('网络错误，请稍后重试');
  }
};

/**
 * 处理返回逻辑
 */
const handleReturn = () => {
  submitting.value = false;
  
  // 返回上一页或首页
  if (getCurrentPages().length > 1) {
    uni.navigateBack();
  } else {
    uni.reLaunch({
      url: '/pages/dog/index'
    });
  }
};

/**
 * 页面卸载时清除定时器
 */
onBeforeUnmount(() => {
  stopCountdown();
});
</script>

<style lang="scss" scoped>
.bind-mobile-page {
  min-height: 100vh;
  padding: 60rpx 40rpx;
  background-color: #fff;
}

.top-section {
  text-align: center;
  margin-bottom: 80rpx;
  
  .logo-img {
    display: block;
    width: 280rpx;
    height: 280rpx;
    border-radius: 24rpx;
    margin: 0 auto 40rpx auto;
  }
  
  .subtitle-text {
    font-size: 28rpx;
    color: #666666;
  }
}

.form-section {
  background: #ffffff;
  border-radius: 24rpx;
  padding: 60rpx 40rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
  
  .form-item {
    margin-bottom: 40rpx;
    
    .form-label {
      font-size: 28rpx;
      color: #333333;
      margin-bottom: 20rpx;
      font-weight: 500;
      
      .required {
        color: #ff6b6b;
        margin-right: 8rpx;
      }
    }
    
    .form-input {
      width: 100%;
      height: 88rpx;
      background: #f5f7fa;
      border-radius: 12rpx;
      padding: 0 24rpx;
      font-size: 28rpx;
      color: #333333;
      border: 2rpx solid transparent;
      transition: all 0.3s;
      
      &:focus {
        background: #ffffff;
        border-color: #667eea;
      }
    }
    
    .code-input-wrapper {
      display: flex;
      align-items: center;
      gap: 20rpx;
      
      .code-input {
        flex: 1;
      }
      
      .code-btn {
        width: 180rpx;
        height: 88rpx;
        background: #31a7fb;
        color: #ffffff;
        border-radius: 12rpx;
        font-size: 24rpx;
        border: none;
        display: flex;
        align-items: center;
        justify-content: center;
        
        &.disabled {
          background: #d0d5dd;
          color: #666666;
        }
        
        &::after {
          border: none;
        }
      }
    }
  }
  
  .submit-btn {
    width: 100%;
    height: 96rpx;
    background: #31a7fb;
    color: #ffffff;
    border-radius: 48rpx;
    font-size: 32rpx;
    font-weight: 500;
    border: none;
    margin-top: 40rpx;
    box-shadow: 0 8rpx 24rpx rgba(49, 167, 251, 0.4);
    
    &::after {
      border: none;
    }
  }
  
  .tips-section {
    margin-top: 40rpx;
    text-align: center;
    font-size: 24rpx;
    color: #999999;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8rpx;
    
    .tips-icon {
      font-size: 28rpx;
    }
  }
}
</style>

